using Light;
using UnityEngine;

public class KnockBackReceiver : CoreComponent, IKnockBackable, ILogicupdateable
{
    [SerializeField] private float maxKnockbackTime = 0.2f;
    private CoreComp<CollisionSenses> collisionSenses;

    private bool isKonckBackActive;
    private float knockBackStartTime;


    private CoreComp<Movement> movement;

    protected override void Awake()
    {
        base.Awake();

        core.AddCoreComponent(this);
        movement = new CoreComp<Movement>(core);
        collisionSenses = new CoreComp<CollisionSenses>(core);
    }


    public void KnockBack(Vector2 angle, float strength, int direction)
    {
        movement.Comp?.SetVelocity(strength, angle, direction);
        isKonckBackActive = true;
        movement.Comp.CanSetVelocity = false;
        knockBackStartTime = Time.time;
    }

    public void LogicUpdate()
    {
        CheckKnockBack();
    }


    private void CheckKnockBack()
    {
        if ((isKonckBackActive &&
             movement.Comp.CurrentVelocity.y <= 0.01f && collisionSenses.Comp.Grounded)
            || Time.time >= knockBackStartTime + maxKnockbackTime)
        {
            isKonckBackActive = false;
            movement.Comp.CanSetVelocity = true;
        }
    }
}